package com.fcai.microserv.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JacksonLocalDateTimeFormatter {

    @JsonComponent
    public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {

        @Value("${spring.mvc.format.date:${spring.jackson.date-format:yyyy-MM-dd}}")
        private String pattern;

        @Override
        public void serialize(LocalDateTime value, JsonGenerator g, SerializerProvider serializers) throws IOException, JsonProcessingException {
            g.writeString(value.format(DateTimeFormatter.ofPattern(pattern)));
        }
    }

    @JsonComponent
    public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

        @Value("${spring.mvc.format.date:${spring.jackson.date-format:yyyy-MM-dd}}")
        private String pattern;

        @Override
        public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String text = p.getText().trim();
            return LocalDateTime.parse(text, DateTimeFormatter.ofPattern(pattern));
        }
    }
}
